package com.example.messengerapp.viewmodel

import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.messengerapp.ui.EditProfileFragment
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage

class EditProfileViewModel : ViewModel() {

    private val _profileImageUri = MutableLiveData<Uri?>()
    val profileImageUri: LiveData<Uri?> get() = _profileImageUri

    fun updateProfileImage(uri: Uri) {
        _profileImageUri.value = uri
    }

    fun saveUserProfile(userProfile: EditProfileFragment.UserProfile, onComplete: (Boolean) -> Unit) {
        val userId = FirebaseAuth.getInstance().currentUser?.uid
        if (userId != null) {
            val databaseReference = FirebaseDatabase.getInstance().getReference("users").child(userId)
            databaseReference.setValue(userProfile).addOnCompleteListener { task ->
                onComplete(task.isSuccessful)
            }
        } else {
            onComplete(false)
        }
    }

    fun uploadProfileImage(uri: Uri, onComplete: (Uri?) -> Unit) {
        val userId = FirebaseAuth.getInstance().currentUser?.uid
        if (userId != null) {
            val storageReference = FirebaseStorage.getInstance().getReference("profile_images/$userId.jpg")
            storageReference.putFile(uri).addOnSuccessListener {
                storageReference.downloadUrl.addOnSuccessListener { downloadUri ->
                    onComplete(downloadUri)
                }
            }.addOnFailureListener {
                onComplete(null)
            }
        } else {
            onComplete(null)
        }
    }
}
